// 封装组合式功能

import { OrderType } from '@/enums'
import { cancelOrder, deleteOrder, followDoctor, getPrescriptionPic } from '@/services/consult'
import type { ConsultOrderItem, DoctorItem, FollowType } from '@/types/consult'
import { showImagePreview, showSuccessToast } from 'vant'
import { ref } from 'vue'

// 命名规范 useXxx
// 关注/取消关注组合式功能
export const useFollow = (type: FollowType) => {
  const loading = ref(false)
  const follow = async (item: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true
    try {
      await followDoctor(item.id, 'doc')
      // 手动修改关注数据字段
      item.likeFlag = item.likeFlag === 0 ? 1 : 0
      loading.value = false
    } catch (error) {
      loading.value = false
    }
  }
  return { loading, follow }
}
// 封装查看处方逻辑
export const useShowPrescription = () => {
  // 查看处方
  const showPrescription = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      showImagePreview([res.data.url])
    }
  }
  return { showPrescription }
}

// 取消订单组合式功能
export const useCancelOrder = () => {
  const loading = ref(false)
  const onCancelOrder = async (item: ConsultOrderItem) => {
    // 开启 loading
    loading.value = true
    try {
      // 调用取消订单接口
      await cancelOrder(item.id)
      // 修改订单状态
      item.status = OrderType.ConsultCancel
      // 修改订单文字
      item.statusValue = '已取消'
      // 成功提示
      showSuccessToast('取消成功')
    } finally {
      // 关闭 loading
      loading.value = false
    }
  }
  return { loading, onCancelOrder }
}

// 删除订单组合式功能
export const useDelOrder = () => {
  const emit = defineEmits<{
    (e: 'on-delete', id: string): void
  }>()
  const delOrder = async (item: ConsultOrderItem) => {
    // 调用删除接口
    await deleteOrder(item.id)
    // 提示用户
    showSuccessToast('删除成功')
    // 前端手动删除该条数据
    emit('on-delete', item.id)
  }
  return { emit, delOrder }
}
